//
//  AIGirlSubscribeViewController.swift
//  AIGirl
//
//  Created by Rae on 2024/1/3.
//

import UIKit
import SwiftyStoreKit

class AIGirlSubscribeViewController: AIGirlBaseViewController, AIGirlLottieAnimationProtocol {
    
    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private lazy var bgImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Subscribe_bg").mode(.scaleAspectFill).end()
    private lazy var shadowView = c_make_ex(UIView.self).end()
    private lazy var bottomView = c_make_ex(UIView.self).bgColor("#120D00").end()
    private lazy var backButton = c_make_ex(UIButton.self)
        .image("AIGirl_Subscribe_back").end()
    private lazy var restoreButton = c_make_ex(UIButton.self)
        .text("Restore").color(.white).font(14.font_semiBold).end()
    private lazy var titleView = c_make_ex(UIImageView.self)
        .image("AIGirl_Subscribe_titleView").mode(.scaleAspectFill).end()
    private var contentV = AIGirlPremiumCotnentView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var animateView: AIGirlLottieAnimationView = {
        lottieAnimation.make(.subscribe)
    }()
    private lazy var nextButton = c_make_ex(UIButton.self)
        .color("#291600").font(21.font_bold).corner(20)
        .text("Continue").end()
    private lazy var termButton = c_make_ex(UIButton.self)
        .color(.white.alpha(0.5)).font(12.font_regular).end()
    private lazy var policyButton = c_make_ex(UIButton.self)
        .color(.white.alpha(0.5)).font(12.font_regular).end()
    
    private var lists: [AIGirlSubscribeItemModel] = [AIGirlSubscribeItemModel]()
    var dismissClosure: (() -> Void)?
    var buyUpdateClosure: (() -> Void)?
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        view.subviews{
            bgImageView
            shadowView
            bottomView
            scrollView.subviews{
                containerView.subviews{
                    titleView
                    contentV
                    collectionView
                    animateView
                    nextButton
                    termButton
                    policyButton
                }
            }
            backButton
            restoreButton
        }
        
        bgImageView.fillContainer()
        scrollView.leading(0).trailing(0).bottom(0).top(0)
        scrollView.contentInsetAdjustmentBehavior = .never
        scrollView.showsVerticalScrollIndicator = false
        containerView.fillContainer().width(.screenWidth)
        shadowView.leading(0).trailing(0).top(0).height(400)
        bottomView.leading(0).trailing(0).bottom(0)
        bottomView.Top == shadowView.Bottom
        backButton.leading(15).top(.statusHeight + 7.0).size(40)
        restoreButton.trailing(15)
        restoreButton.CenterY == backButton.CenterY
       
        var topMagin = 190.0
        if Double.isIPhoneX {
            topMagin = CGFloat.statusHeight + 207.0
        }
        titleView.leading(17).height(24).width(170).top(topMagin)
//        titleView.Top == backButton.Bottom + 160
        contentV.leading(0).trailing(0).height(250)
        contentV.Top == titleView.Bottom + 15
        collectionView.leading(0).trailing(0).height(155)
        collectionView.Top == contentV.Bottom + 20
        nextButton.leading(20).trailing(20).height(50)
        nextButton.Top == collectionView.Bottom + 30
        animateView.leading(0).trailing(0).height(90)
        animateView.CenterY == nextButton.CenterY
        termButton.trailing(.screenWidth/2 + 25).bottom(25)
        termButton.Top == nextButton.Bottom + 25
        policyButton.leading(.screenWidth/2 + 25).bottom(25)
        policyButton.Top == nextButton.Bottom + 25

        termButton.style { v in
            let attributedString = NSAttributedString(string: "Term of Us", attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
            v.setAttributedTitle(attributedString, for: .normal)
            v.addTarget(self, action: #selector(clickTermButton), for: .touchUpInside)
        }
        policyButton.style { v in
            let attributedString = NSAttributedString(string: "Privacy Policy", attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
            v.setAttributedTitle(attributedString, for: .normal)
            v.addTarget(self, action: #selector(clickPolicyButton), for: .touchUpInside)
        }

        let w = (CGFloat.screenWidth - 45.0) / 3
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: w, height: 155)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.5, bottom: 0, right: 12.5)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlSubscribeItem.self, forCellWithReuseIdentifier: AIGirlSubscribeItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        backButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        restoreButton.addTarget(self, action: #selector(clickedControlRestore), for: .touchUpInside)
        
        let bgUrl = UserDefaultsManager.getString(forKey: .girlAvatar)
        bgImageView.loadImage(url: bgUrl)
    }
    
    private func loadData(){
        
        request.start(.vipList, type: AIGirlSubscribeModel.self) { result in
            
            if result.isSuccessful,let model = result.model {
                for index in 0..<model.lists.count {
                    var model = model.lists[index]
                    if model.period == 5 {
                        model.isSel = true
                    }else{
                        model.isSel = false
                    }
                    self.lists.append(model)
                }
                self.collectionView.reloadData()
            }
            
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        shadowView.fj.gradientColors(.topToBottom(["#000000".toColor.alpha(0),"#120D00".toColor]))
        nextButton.fj.gradientColors(.leftToRight(["#FAC17C".toColor,"#F1DFB3".toColor]))
    }

}

//MARK: action
extension AIGirlSubscribeViewController {
    
    @objc private func clickNextButton() {
        
        if lists.count == 0 {
            return
        }
        
        var model = AIGirlSubscribeItemModel()
        for md in lists {
            if md.isSel {
                model = md
            }
        }        
        purchaseProduct(productCode: model.code, productId: String(model.id))
    }
    
    @objc private func clickedControlRestore() {
        AIGirlApplePay.default.restorePurchases {
            self.buyUpdateClosure?()
            self.dismiss(animated: true)
        }
//        Task {
//            ToastTool.show()
//            SwiftyStoreKit.restorePurchases(atomically: false) { results in
//                if results.restoreFailedPurchases.count > 0 {
//                    ToastTool.dismiss()
//                    print("Restore Failed: \(results.restoreFailedPurchases)")
//                }
//                else if results.restoredPurchases.count > 0 {
//                    for (purchaseIndex , purchase) in results.restoredPurchases.enumerated() {
//                        //发送最后一条票据
//                        if purchaseIndex == results.restoredPurchases.count - 1 {
//                            //验证票据
//                            Task {
//                                if let localReceiptData = SwiftyStoreKit.localReceiptData {
//                                    let base64 = localReceiptData.base64EncodedString()                                    
//                                    self.request.start(.subscription(code: purchase.productId, orderId: "", baseStr: base64),type: AIGirlVIPModel.self) { result in
//                                        if result.isSuccessful, let model = result.model {
//                                            
//                                            AIGirlApplePayCache.shared.sub_productIdentifier = nil
//                                            SwiftyStoreKit.finishTransaction(purchase.transaction)
//                                            "Successful".toast_success
//                                            GlobalTool.refreshUserInfo()
//                                            UserDefaultsManager.setString(model.createTime.toTimeStr(), forKey: .VIPStartTime)
//                                            UserDefaultsManager.setString(model.expirationTime.toTimeStr(), forKey: .VIPEndTime)
//                                            self.buyUpdateClosure?()
//                                            self.dismiss(animated: true)
//                                        }else {
//                                            result.errorDescripton?.toast_error
//                                        }
//                                    }
//
//                                }
//                            }
//                        }
//
//                        // fetch content from your server, then:
//                        if purchase.needsFinishTransaction {
//                            /// 清空缓存
//                            AIGirlApplePayCache.shared.sub_productIdentifier = nil
//                            SwiftyStoreKit.finishTransaction(purchase.transaction)
//                        }
//                    }
//                    print("Restore Success: \(results.restoredPurchases)")
//                }
//                else {
//                    print("Nothing to Restore")
//                    ToastTool.dismiss()
//                }
//            }
//        }
    }
    
    @objc private func clickTermButton(_ sender: UIButton){
        let webVc = AIGirlWebViewController()
        webVc.urlString = AGirlConstants.terms
        webVc.titleName = sender.titleLabel?.text
        self.navigationController?.pushViewController(webVc, animated: true)
    }
    
    @objc private func clickPolicyButton(_ sender: UIButton){
        let webVc = AIGirlWebViewController()
        webVc.urlString = AGirlConstants.policy
        webVc.titleName = sender.titleLabel?.text
        self.navigationController?.pushViewController(webVc, animated: true)
    }
    
    @objc private func clickCloseButton(){
        self.dismiss(animated: true){
            self.dismissClosure?()
        }
    }
    
    func purchaseProduct(productCode: String, productId: String) {
        Task{
            ToastTool.show()
            guard let model = await purchaseTool.createOrder(productId: productId) else {
                return
            }
            AIGirlApplePay.default.subscription(id: productCode, orderId: model.id) {
                self.buyUpdateClosure?()
                self.dismiss(animated: true)
            }
//            var productId = AIGirlApplePayCache.shared.sub_productIdentifier
//            if productId == nil {
//                productId = product.productIdentifier
//            }
//            let result1 = await StoreKitTool.purchaseProduct(purchaseID: productId ?? "", orderNo: "" )
//            guard let verifyData = result1.data else {
//                ToastTool.dismiss()
//                return
//            }
//            guard let ticket = verifyData.1 else {
//                ToastTool.dismiss()
////                "payId 为空".toast_error
//                return
//            }
//            request.start(.subscription(code: productCode, orderId: model.id, baseStr: ticket),type: AIGirlVIPModel.self) { result in
//                if result.isSuccessful, let model = result.model {
//                    /// 清空缓存
//                    AIGirlApplePayCache.shared.sub_productIdentifier = nil
//                    
//                    SwiftyStoreKit.finishTransaction(verifyData.0.transaction)
//                    "Successful".toast_success
//                    GlobalTool.refreshUserInfo()
//                    UserDefaultsManager.setString(model.createTime.toTimeStr(), forKey: .VIPStartTime)
//                    UserDefaultsManager.setString(model.expirationTime.toTimeStr(), forKey: .VIPEndTime)
//                    self.buyUpdateClosure?()
//                    self.dismiss(animated: true)
//                }else {
//                    result.errorDescripton?.toast_error
//                    
//                    AIGirlApplePayCache.shared.sub_productIdentifier = product.productIdentifier
//                }
//            }
        }
    }
}

extension AIGirlSubscribeViewController: UICollectionViewDelegate, UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return lists.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlSubscribeItem.description(), for: indexPath) as? AIGirlSubscribeItem else { return UICollectionViewCell() }
        item.model = lists[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlSubscribeItemModel]()
        lists.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        lists = models
        collectionView.reloadData()
    }
}


class AIGirlSubscribeItem: UICollectionViewCell {
    
    private lazy var bgView = AIGirlRoundedCornersView(topLeftRa: 15, topRightRa: 25, bottomLeftRa: 25, bottomRightRa: 15)
    private lazy var bgImgView = c_make_ex(UIImageView.self)
        .image(UIImage.colorToImage(color: .white.alpha(0.13))).end()
    private lazy var selImg = c_make_ex(UIImageView.self)
        .image("AIGirl_Subscribe_sel").end()
    private lazy var labelImg = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private lazy var timeLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.6)).font(30.font_bold).alignment(.center).end()
    private lazy var unitLabel = c_make_ex(UILabel.self).text("MONTHS")
        .color(.white.alpha(0.6)).font(16.font_semiBold).alignment(.center).end()
    private lazy var contentLabel = c_make_ex(UILabel.self)
        .font(10.font_regular).color(.white.alpha(0.6)).alignment(.center).end()
    private lazy var moneyLabel = c_make_ex(UILabel.self)
        .font(16.font_semiBold).color(.white.alpha(0.6)).alignment(.center).end()
    private lazy var bottomLabel = c_make_ex(UILabel.self)
        .font(12.font_medium).color(.white.alpha(0.6)).alignment(.center).end()
    
    var model: AIGirlSubscribeItemModel? {
        didSet{
            guard let md = model else { return }
            selImg.isHidden = !md.isSel
            moneyLabel.text = "$ " + md.price
            contentLabel.text = "SGD " + md.periodPrice
            bgImgView.image = UIImage.colorToImage(color: .white.alpha(0.13))
            if md.period == 1 {
                timeLabel.text = "1"
                bottomLabel.text = "Per month"
                labelImg.isHidden = true
            }else{
                labelImg.isHidden = false
                if md.period == 5 {
                    timeLabel.text = "12"
                    labelImg.image = "AIGirl_Subscribe_best".toImage
                    bottomLabel.text = "Per year"
                    bgImgView.image = "AIGirl_Subscribe_month".toImage
                }else if md.period == 3 {
                    timeLabel.text = "3"
                    labelImg.image = "AIGirl_Subscribe_popular".toImage
                    bottomLabel.text = "Per 3 month"
                }
            }
        }
    }
            
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.subviews {
            bgView.subviews{
                bgImgView
            }            
            selImg
            labelImg
            timeLabel
            unitLabel
            contentLabel
            moneyLabel
            bottomLabel
        }

        bgView.fillContainer()
        bgImgView.fillContainer()
        selImg.fillContainer()
        labelImg.leading(0).top(0).width(64).height(46)
        timeLabel.top(18).centerHorizontally()
        unitLabel.centerHorizontally()
        unitLabel.Top == timeLabel.Bottom - 1
        contentLabel.centerHorizontally()
        contentLabel.Top == unitLabel.Bottom + 5
        moneyLabel.centerHorizontally()
        moneyLabel.Top == contentLabel.Bottom + 15
        bottomLabel.centerHorizontally().bottom(6)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class AIGirlPremiumCotnentView: UIView {
     
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        let contentOne = setupTitleContent(title: "Unlock Intimate Conversations.", img: "AIGirl_Subscribe_lock")
        let contentTwo = setupTitleContent(title: "Double Increase in Intimacy Values.", img: "AIGirl_Subscribe_heard")
        let contentThree = setupTitleContent(title: "View premium photos for free", img: "AIGirl_Subscribe_look")
        let contentFour = setupTitleContent(title: "Exclusive VIP avatar", img: "AIGirl_Subscribe_guan")
        let contentFive = setupTitleContent(title: "Get 2x diamonds every day", img: "AIGirl_Subscribe_diamond")
        let sixImg = UIImageView(image: "AIGirl_Subscribe_pic".toImage)
        let sixLab = UILabel()
        sixLab.style { v in
            v.text = "Complimentary Download of AI High-Resolution Selfies."
            v.numberOfLines = 0
            v.textColor = .white.alpha(0.8)
        }
        
        subviews{
            contentOne
            contentTwo
            contentThree
            contentFour
            contentFive
            sixImg
            sixLab
        }
        
        contentOne.leading(17).trailing(45).top(0)
        contentTwo.leading(17).trailing(45)
        contentTwo.Top == contentOne.Bottom + 10
        contentThree.leading(17).trailing(45)
        contentThree.Top == contentTwo.Bottom + 10
        contentFour.leading(17).trailing(45)
        contentFour.Top == contentThree.Bottom + 10
        contentFive.leading(17).trailing(45)
        contentFive.Top == contentFour.Bottom + 10
        sixImg.leading(17).size(20)
        sixImg.Top == contentFive.Bottom + 10
        sixLab.leading(47).trailing(45)
        sixLab.Top == sixImg.Top
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupTitleContent(title: String, img: String) -> UIIconButton{
        
        let titleBtn = UIIconButton(style: .leading(itemSpace: 10))
        titleBtn.setTitle(title, for: .normal)
        titleBtn.setImage(img.toImage, for: .normal)
        titleBtn.setTitleColor(.white.alpha(0.8), for: .normal)
        titleBtn.titleLabel?.font = 15.font_medium
        titleBtn.iconSize = CGSize(width: 20, height: 20)
        titleBtn.isUserInteractionEnabled = false
        titleBtn.contentHorizontalAlignment = .leading
        
        return titleBtn
    }
}
